package com.mystery.action;

import com.mystery.pojo.FitnessDiary;
import com.mystery.pojo.User;
import com.mystery.service.FitnessDiaryService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import javax.annotation.Resource;
import java.util.List;

public class FitnessDiaryAction extends ActionSupport implements ModelDriven<FitnessDiary>{

    @Resource
    private FitnessDiaryService fitnessDiaryService;

    private FitnessDiary fitnessDiary = new FitnessDiary();

    private List<FitnessDiary> fitnessDiaryList;

    public List<FitnessDiary> getFitnessDiaryList() {
        return fitnessDiaryList;
    }

    public void setFitnessDiaryList(List<FitnessDiary> fitnessDiaryList) {
        this.fitnessDiaryList = fitnessDiaryList;
    }

    public String myFitnessDiary(){
        User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
        if(user == null){
            ServletActionContext.getRequest().setAttribute("error","请先登录!");
            return "findError";
        }
        fitnessDiaryList  = fitnessDiaryService.findAllById(user.getId());
        if(fitnessDiaryList == null || fitnessDiaryList.size() == 0){
            ServletActionContext.getRequest().setAttribute("error","您还没有健身日记赶快写一个吧!");
            return "findError";
        }
        return "myFitnessDiary";
    }

    public String add(){
        User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
        if(user == null){
            ServletActionContext.getRequest().setAttribute("error","请先登录!");
            return "add_error";
        }
        long userId = user.getId();
        String fitnessDiary = ServletActionContext.getRequest().getParameter("fitnessDiary");
        int add = fitnessDiaryService.add(userId, fitnessDiary);
        if(add > 0){
            return "add_ok";
        }
        ServletActionContext.getRequest().setAttribute("error","录入失败请重试!");
        return "add_error";
    }
    @Override
    public FitnessDiary getModel() {
        return fitnessDiary;
    }
}
